#import "FretBoardView.h"


@implementation FretBoardView

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	app = [ChordsApplication sharedInstance];
	currentChord = [[ChordString alloc] init];

	selectedChord=atoi([[[app getApplState] getChordState] lossyCString]);
	selectedMode=atoi([[[app getApplState] getModeState] lossyCString]);
	fromStatePosition=atoi([[[app getApplState] getPositionState] lossyCString])+1;
	notation=[[app getApplState] getNotationState];
	
	NSLog([NSString stringWithFormat:@"selectedChord <%d>.selectedMode <%d>.selectedNotation <%@>",selectedChord,selectedMode,notation]);
		
	notationDict = [[NSDictionary dictionaryWithContentsOfFile: [NSString stringWithFormat:@"%@/resources/NotationDict.plist", [[NSBundle mainBundle] bundlePath]]] retain];
	if ([notation length]==0) 
		notation=NSLocalizedStringFromTable(@"Notation", @"Chords", @"Notation");
	[notation retain];
	NSLog([NSString stringWithFormat:@"Start Notation <%@>",notation]);

	float white[] = {1, 1, 1, 1};
	float alpha[] = {0, 0, 0, 0};

    struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

	mainView = [[UIView alloc] initWithFrame: rect];

	int i;
	//-------------------------------------------------
	// BACKGROUND
	//-------------------------------------------------
	// UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y+40, rect.size.width, rect.size.height)] autorelease];
	UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)] autorelease];
	[background setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"background" ofType:@"png" inDirectory:@"/images"]] retain]];
	[mainView addSubview: background];

	chord = [[NSArray arrayWithObjects:@"C", @"Cs", @"D", @"Ds", @"E", @"F", @"Fs", @"G", @"Gs", @"A", @"As", @"B", nil] retain];
	mode = [[NSArray arrayWithObjects:@"maj", @"m", @"maj7", @"dim7", @"sus2", @"sus4", @"6", @"7", @"7+", @"7b5", @"7#9", @"9", @"11", @"13", @"m6",@"m7",@"+",@"m7b5",@"7sus4",@"add9",@"m9", nil] retain];

	struct __GSFont *smallFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:10];
	struct __GSFont *mediumFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:16];
	struct __GSFont *bigFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:22];
	
	btnImageStroke = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"stroke" ofType:@"png" inDirectory:@"/images"]];
	btnImageNoStroke = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"no" ofType:@"png" inDirectory:@"/images"]];
	
	btnImageChord = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"btn1" ofType:@"png" inDirectory:@"/images"]];
	btnImageMode = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"btn2" ofType:@"png" inDirectory:@"/images"]];
	buttonImagePressed = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"btn-x" ofType:@"png" inDirectory:@"/images"]];
	btnImageSelected = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"btn-x" ofType:@"png" inDirectory:@"/images"]];
	
	btnImagePrev = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"prev" ofType:@"png" inDirectory:@"/images"]];
	btnImageNext = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"next" ofType:@"png" inDirectory:@"/images"]];
	btnImagePrevPressed = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"prevPressed" ofType:@"png" inDirectory:@"/images"]];
	btnImageNextPressed = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"nextPressed" ofType:@"png" inDirectory:@"/images"]];
	
	btnImageRecPressed = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"recPressed" ofType:@"png" inDirectory:@"/images"]];
	
	btnImagePlay = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"play" ofType:@"png" inDirectory:@"/images"]];
	btnImagePlayPressed = [UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"playPressed" ofType:@"png" inDirectory:@"/images"]];
	
	chordButtons = [[NSMutableArray alloc] initWithCapacity:12];
	modeButtons = [[NSMutableArray alloc] initWithCapacity:16];
	dotImages = [[NSMutableArray alloc] initWithCapacity:6];
	fretText = [[NSMutableArray alloc] initWithCapacity:6];

	for(i = 0; i < [chord count]; i++)
	{
		NSLog([NSString stringWithFormat:@"CHORD %@", [chord objectAtIndex:i]]);
		int row = i / 6;
		float x = 1 + ((i % 6)*53);
		float y = 222 + (38 * row)+DELTA;

		NSString *key=[NSString stringWithFormat:@"%@.%@", notation ,[chord objectAtIndex:i]];
		NSLog([NSString stringWithFormat: @"KEY: <%@>", key]);
		NSString *chordNotation = [notationDict objectForKey:key];
				
		UIPushButton *theButton = [[UIPushButton alloc] initWithTitle:chordNotation autosizesToFit:NO];
		[theButton setFrame: CGRectMake(x, y, 53.0, 38.0)];
		[theButton setDrawsShadow: NO];
		[theButton setStretchBackground:NO];
		if (i==selectedChord) {
			[theButton setBackground:btnImageSelected forState:0];
		} else {
			[theButton setBackground:btnImageChord forState:0];
		}
		[theButton setBackground:buttonImagePressed forState:1];
		if ([[chord objectAtIndex:i] length]==1)
		{
			[theButton setTitleFont:mediumFont];
		} else {
		
			[theButton setTitleFont:smallFont];
		}
		[theButton setDrawContentsCentered:YES];
//		[theButton setTitlePadding:CGSizeMake(60.0, 12.0)];
		[theButton addTarget:self action:@selector(chordButtonsPressed:) forEvents:kUIControlEventMouseUpInside];
		[chordButtons addObject:theButton];
		
		[mainView addSubview: theButton];	
	}
	
	for(i = 0; i < [mode count]; i++)
	{
		NSLog([NSString stringWithFormat:@"MODE %@", [mode objectAtIndex:i]]);
		int row = i / 6;
		float x = 1 + ((i % 6)*53);
		float y = 304 + (38 * row)+DELTA;
		UIPushButton *theButton = [[UIPushButton alloc] initWithTitle:[NSString stringWithFormat:@"%@", [mode objectAtIndex:i]] autosizesToFit:NO];
		[theButton setFrame: CGRectMake(x, y, 53.0, 38.0)];
		[theButton setDrawsShadow: NO];
		[theButton setStretchBackground:NO];
		if (i==selectedMode) {
			[theButton setBackground:btnImageSelected forState:0];
		} else {
			[theButton setBackground:btnImageMode forState:0];
		}
		[theButton setBackground:buttonImagePressed forState:1];
		[theButton setTitleFont:mediumFont];
		[theButton setDrawContentsCentered:YES];
		[theButton setTitlePadding:CGSizeMake(60.0, 12.0)];
		[theButton addTarget:self action:@selector(modeButtonsPressed:) forEvents:kUIControlEventMouseUpInside];
		[modeButtons addObject:theButton];
		
		[mainView addSubview: theButton];	
	}
	
	for(i = 0; i < 6; i++)
	{
		UIImageView *dot = [[UIImageView alloc] init];
		[dotImages addObject:dot];
		[mainView addSubview: dot];
	}
	
	for(i = 0; i < 5; i++)
	{
		UITextLabel *fret = [[UITextLabel alloc] initWithFrame:CGRectMake(34+(i*64), 42.0+DELTA, 24.0, 16.0)];
		[fret setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), alpha)];
		[fret setColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), white)];
		[fret setFont:smallFont];
		[fretText addObject:fret];
		[mainView addSubview: fret];
	}

	strings = [[UIImageView alloc] initWithFrame:CGRectMake(2.0, 66.0+DELTA ,7.0,143.0)];
	[strings setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"strings" ofType:@"png" inDirectory:@"/images"]] retain]];
	[mainView addSubview:strings];
	[mainView bringSubviewToFront:strings];
		
	label = [[UIPushButton alloc] initWithTitle:@"" autosizesToFit:NO];
	[label setFrame:CGRectMake(83.0+DELTA_BUTTON, 426.0+DELTA, 44.0, 32.0)];
	[label setDrawsShadow: NO];
	[label setStretchBackground:NO];
	[label setTitleFont:mediumFont];
	[label setDrawContentsCentered:YES];
	[label setTitlePadding:CGSizeMake(44.0, 32.0)];	
	[label setBackground:btnImageRecPressed forState:1];
	[label addTarget:self action:@selector(labelButtonPressed:) forEvents:kUIControlEventMouseUpInside];		
	[mainView addSubview: label];	
/*
	NSString *scales = NSLocalizedStringFromTable(@"Scales", @"Chords", @"Scales");

	scales = [[UIPushButton alloc] initWithTitle:scales autosizesToFit:NO];
	[scales setFrame:CGRectMake(-52.0+DELTA_BUTTON, 424.0+DELTA, 53.0, 32.0)];
	[scales setDrawsShadow: NO];
	[scales setStretchBackground:NO];
	[scales setTitleFont:mediumFont];
	[scales setDrawContentsCentered:YES];
	[scales setTitlePadding:CGSizeMake(53.0, 32.0)];	
	[scales setBackground:buttonImagePressed forState:1];
	[scales addTarget:self action:@selector(scalesButtonPressed:) forEvents:kUIControlEventMouseUpInside];		

	[mainView addSubview: scales];	
*/	
	prev = [[UIPushButton alloc] initWithFrame:CGRectMake(54.0+DELTA_BUTTON, 422.0+DELTA, 30.0, 37.0)];
	[prev setAutosizesToFit:NO];
	[prev setDrawsShadow: NO];
	[prev setStretchBackground:NO];
	[prev setBackground:btnImagePrev forState:0];
	[prev setBackground:btnImagePrevPressed forState:1];
	[prev setDrawContentsCentered:YES];
	[prev addTarget:self action:@selector(prevButtonPressed:) forEvents:kUIControlEventMouseUpInside];
	
	next = [[UIPushButton alloc] initWithFrame:CGRectMake(128.0+DELTA_BUTTON, 422.0+DELTA, 30.0, 37.0)];
	[next setAutosizesToFit:NO];
	[next setDrawsShadow: NO];
	[next setStretchBackground:NO];
	[next setBackground:btnImageNext forState:0];
	[next setBackground:btnImageNextPressed forState:1];
	[next setDrawContentsCentered:YES];
	[next addTarget:self action:@selector(nextButtonPressed:) forEvents:kUIControlEventMouseUpInside];

	UIImageView *prevImageDisabled = [[UIImageView alloc] init];
	[prevImageDisabled setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"prevDisabled" ofType:@"png" inDirectory:@"/images"]] retain]];
	[prevImageDisabled setFrame: CGRectMake(54.0+DELTA_BUTTON, 422.0+DELTA, 30.0, 37.0)];
	[mainView addSubview: prevImageDisabled];

	UIImageView *nextImageDisabled = [[UIImageView alloc] init];
	[nextImageDisabled setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"nextDisabled" ofType:@"png" inDirectory:@"/images"]] retain]];
	[nextImageDisabled setFrame: CGRectMake(128.0+DELTA_BUTTON, 422.0+DELTA, 30.0, 37.0)];
	[mainView addSubview: nextImageDisabled];

	UIImageView *playImageDisabled = [[UIImageView alloc] init];
	[playImageDisabled setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"playDisabled" ofType:@"png" inDirectory:@"/images"]] retain]];
	[playImageDisabled setFrame: CGRectMake(6.0+DELTA_BUTTON, 422.0+DELTA, 40.0, 37.0)];
	[mainView addSubview: playImageDisabled];
/*
	play = [[UIPushButton alloc] initWithFrame:CGRectMake(6.0+DELTA_BUTTON, 422.0+DELTA, 40.0, 37.0)];
	[play setAutosizesToFit:NO];
	[play setDrawsShadow: NO];
	[play setStretchBackground:NO];
	[play setBackground:btnImagePlay forState:0];
	[play setBackground:btnImagePlayPressed forState:1];
	[play setDrawContentsCentered:YES];
	[play addTarget:self action:@selector(playButtonPressed:) forEvents:kUIControlEventMouseUpInside];
	[mainView addSubview: play];
*/
	[currentChord setChord:[chord objectAtIndex:selectedChord]];
	[currentChord setMode:[mode objectAtIndex:selectedMode]];
	[self drawChord];

	[self addSubview:mainView];	
		
	return self;

}

-(void)drawChord
{
	chordPositions = [[[currentChord getChordPosition] componentsSeparatedByString:@":"] retain];
	numChordPositions = [chordPositions count];
	if (fromStatePosition>0)
	{
		selectedPosition=fromStatePosition-1;
		fromStatePosition=0;
	} else {
		selectedPosition=atoi([[[app getApplState] getPreferredState:[NSString stringWithFormat:@"%@-%@",
				[chord objectAtIndex:selectedChord],[mode objectAtIndex:selectedMode]]] lossyCString]);
	}
	NSLog([NSString stringWithFormat:@"selectedPosition=%d",selectedPosition]);
	if (numChordPositions>1) {
		if (selectedPosition==0) { // prima positione
			[mainView addSubview: next];
			[prev removeFromSuperview];
		} else if (selectedPosition+1==numChordPositions) { //ultima posizione
			[mainView addSubview: prev];
			[next removeFromSuperview];
		} else {
				[mainView addSubview: prev];
				[mainView addSubview: next];
		}
	} else {
		[next removeFromSuperview];
		[prev removeFromSuperview];
	}
	
	NSLog([NSString stringWithFormat:@"count=%d",numChordPositions]);
	NSString *actualPosition=[chordPositions objectAtIndex:selectedPosition];
	[self drawDots:actualPosition];
}

-(void)drawDots:(NSString *)actualPosition
{
	// [labelPosition setText:[NSString stringWithFormat:@"%d/%d",selectedPosition+1,numChordPositions]];
	[label setTitle:[NSString stringWithFormat:@"%d/%d",selectedPosition+1,numChordPositions]];
	int i;
	unsigned int len = [actualPosition length];
	char buffer[len+ 1];
	buffer[len] = '\0';
	strncpy(buffer, [actualPosition lossyCString], len);
	int min=99;
	int max=0;
	for (i=0; i<6;i++)
	{
		switch (buffer[i]) {
		case 'x' :
		case '0':
			break;
		case 'A':
		case 'B':
		case 'C':
		case 'D':
		case 'E':
		case 'F':
			if ((buffer[i]-'A'+10)<min) min=(buffer[i]-'A'+10);
			if ((buffer[i]-'A'+10)>max) max=(buffer[i]-'A'+10);
			break;		
		default:
			if ((buffer[i]-'0')<min) min=(buffer[i]-'0');
			if ((buffer[i]-'0')>max) max=(buffer[i]-'0');
			break;
		}
	}
	NSLog([NSString stringWithFormat:@"min=%d",min]);
	if (((min<5) && (max<5)) || (min==99)) min=0;
	if (min==0) min++;
	for (i=0; i<6;i++)
	{
		if (i<5)
		{
			UITextLabel *fret = [fretText objectAtIndex:i];
			[fret setText: [NSString stringWithFormat:@"%d", (min+i)]];
		}
		
		UIImageView *dot = [dotImages objectAtIndex:i];
		// NSLog([NSString stringWithFormat: @"String %d Position %c", i, buffer[i]]);
		float x;
		float y;
		y=62+(26*i)+DELTA;
		
		switch (buffer[i]) {
		case 'x' :
			x=16;
			[dot setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"no" ofType:@"png" inDirectory:@"/images"]] retain]];
			[dot setFrame: CGRectMake(x, y, 20.0, 21.0)];
			break;
		case '0':
			x=0.0;
			[dot setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"open" ofType:@"png" inDirectory:@"/images"]] retain]];
			[dot setFrame: CGRectMake(x, y, 15.0, 20.0)];
			break;
		case 'A':
		case 'B':
		case 'C':
		case 'D':
		case 'E':
		case 'F':
			x=34+(64*(buffer[i]-'A'+9-(min-1)));
			[dot setFrame: CGRectMake(x, y, 18.0, 18.0)];
			[dot setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"stroke" ofType:@"png" inDirectory:@"/images"]] retain]];
			break;
		default:
			x=34+(64*(buffer[i]-'1'-(min-1)));
			[dot setFrame: CGRectMake(x, y, 18.0, 18.0)];
			[dot setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"stroke" ofType:@"png" inDirectory:@"/images"]] retain]];
			break;
		}
		// NSLog([NSString stringWithFormat:@"x=%f, y=%f",x,y]);
	}
}

- (int)getSelectedChord
{
	return selectedChord;
}

- (int)getSelectedMode
{
	return selectedMode;
}

- (int)getSelectedPosition
{
	return selectedPosition;
}

- (NSString*)getSelectedNotation
{
	return notation;
}

// DELEGATE METHODS
- (void)chordButtonsPressed:(UIPushButton *)button
{
	NSLog(@"chordButtonsPressed");
	[[chordButtons objectAtIndex:selectedChord] setBackground:btnImageChord forState:0];
	int i = 0;
	while(i < [chord count]) {
			if(button == [chordButtons objectAtIndex:i]) {
				UIPushButton *theButton = [chordButtons objectAtIndex:i];
				[theButton setBackground:btnImageSelected forState:0];
				selectedChord = i;
				break;
			}
			i++;
	}

	NSLog([NSString stringWithFormat: @"CHORD: %@", [chord objectAtIndex:selectedChord]]);
	[currentChord setChord:[chord objectAtIndex:selectedChord]];
	[self drawChord];
}

// DELEGATE METHODS
- (void)modeButtonsPressed:(UIPushButton *)button
{
	NSLog(@"modeButtonsPressed");
	[[modeButtons objectAtIndex:selectedMode] setBackground:btnImageMode forState:0];
	int i = 0;
	while(i < [mode count]) {
			if(button == [modeButtons objectAtIndex:i]) {
				UIPushButton *theButton = [modeButtons objectAtIndex:i];
				[theButton setBackground:btnImageSelected forState:0];
				selectedMode = i;
				break;
			}
			i++;
	}

	NSLog([NSString stringWithFormat: @"MODE: %@", [mode objectAtIndex:selectedMode]]);
	[[app getApplState] setModeState:[NSString stringWithFormat:@"%d",selectedMode]];
	[currentChord setMode:[mode objectAtIndex:selectedMode]];
	[self drawChord];
}

- (void)labelButtonPressed:(UIPushButton *)button
{
	NSLog(@"labelButtonPressed");
	UIAlertSheet *recAlertSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0, 240, 320, 260)];
	[recAlertSheet setContext:@"record"];
	NSString *title= NSLocalizedStringFromTable(@"RecordTitle", @"Chords", @"Record Favorite Position");
	[recAlertSheet setTitle:title];
	NSString *question = NSLocalizedStringFromTable(@"RecordQuestion", @"Chords", @"Are You Sure ?");
	[recAlertSheet setBodyText:question];
	[recAlertSheet addButtonWithTitle:@"No"];
	NSString *yes = NSLocalizedStringFromTable(@"Yes", @"Chords", @"Yes");
	[recAlertSheet addButtonWithTitle:yes];
	[recAlertSheet setRunsModal:YES];		
	[recAlertSheet setNumberOfRows:1];
	[recAlertSheet setDelegate:self];
	[recAlertSheet setAlertSheetStyle:0];
	[recAlertSheet popupAlertAnimated:YES atOffset:150];
}
/*
- (void)scalesButtonPressed:(UIPushButton *)button
{
	NSLog(@"sclalesButtonPressed");
}
*/
- (void)prevButtonPressed:(UIPushButton *)button
{
	NSLog(@"prevButtonPressed");
	selectedPosition--;
	if (selectedPosition==0) [prev removeFromSuperview];	
	[mainView addSubview: next];
	NSString *actualPosition=[chordPositions objectAtIndex:selectedPosition];
	[self drawDots:actualPosition];
}

- (void)nextButtonPressed:(UIPushButton *)button
{
	NSLog(@"nextButtonPressed");
	selectedPosition++;
	if (numChordPositions==selectedPosition+1) [next removeFromSuperview];
	[mainView addSubview: prev];
	NSString *actualPosition=[chordPositions objectAtIndex:selectedPosition];
	[self drawDots:actualPosition];
}

- (void)playButtonPressed:(UIPushButton *)button
{
	NSLog(@"playButtonPressed");
	NSLog([NSString stringWithFormat:@"%@/sounds/%@-%@.wav", [[NSBundle mainBundle] bundlePath],[chord objectAtIndex:selectedChord],[mode objectAtIndex:selectedMode]]);
	NSString *audio=[NSString stringWithFormat:@"%@/sounds/%@-%@.wav", [[NSBundle mainBundle] bundlePath],[chord objectAtIndex:selectedChord],[mode objectAtIndex:selectedMode]];
	NSLog(audio);
	GSEventPlaySoundAtPath(audio);
}

- (void)changeNotation
{
	NSLog(@"changeNotation");
	if (strcmp([notation cString],"Literal"))
	{
		notation = [[NSString stringWithFormat:@"Literal"] retain];
	} else {
		notation = [[NSString stringWithFormat:@"Classic"] retain];
	}
	[[app getApplState] setNotationState:notation];
	int i;
	for(i = 0; i < 12; i++)
	{
		UIPushButton *theButton = [chordButtons objectAtIndex:i];
		NSString *key=[NSString stringWithFormat:@"%@.%@", notation ,[chord objectAtIndex:i]];
		NSLog([NSString stringWithFormat: @"KEY: <%@>", key]);
		NSString *chordNotation = [notationDict objectForKey:key];
		[theButton setTitle:[NSString stringWithFormat:@"%@", chordNotation]];
	}
}

- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
	[sheet dismiss];
	NSLog([sheet context]);
	if ([[sheet context] isEqual:@"record"])
	{
		if ( button == 2 )
		{
			NSLog([NSString stringWithFormat:@"Record %d position for chord %@ mode %@",selectedPosition+1,
				[chord objectAtIndex:selectedChord],[mode objectAtIndex:selectedMode]]);
			[[app getApplState] setPreferredState:[NSString stringWithFormat:@"%d",selectedPosition] forChordType:[NSString stringWithFormat:@"%@-%@",
				[chord objectAtIndex:selectedChord],[mode objectAtIndex:selectedMode]]];
		}
	}
}

@end